import requests
import sys

from bs4 import BeautifulSoup as bs

from plugins.plugin import Plugin

sys.path.append("..")
from src.torrent import Torrent
from src.history import History
from src.config import Config

class BitTorrent(Plugin):

    def __init__(self, history: History=History(), config: Config=Config()) -> None:
        super().__init__(history, config)

        self.history = history
        self.config = config

        self.name = "[-] BitTorrent"
        self.category = "BitTorrent"

        self.params = {
            'instance' : False
        }

        self.flag = "-bt"
        self.full_flag = "--bittorrent"
        self.flag_help = "show torrents from popular trackers"
        self.flag_action = "store_true"

    def get_torrent(self, instance):
        torrents = list()

        html = requests.get("https://torrenther.com/")
        soup = bs(html.text, 'html.parser')

        for video_box in soup.find_all("div", {"class": "d1shortss"}):
            vpage_url = video_box.find("a", href=True)['href']
            title = video_box.find("a", {"class" : "d1short-name"}).text

            v_html = requests.get(vpage_url)
            v_soup = bs(v_html.text, 'html.parser')

            torrent_url = v_soup.find("div", {"id": "download"}).find("a", href=True)['href']
            print(title, torrent_url)

            torrent = Torrent(title=title, url=torrent_url)
            torrents.append(torrent.to_json())
        
        return torrents

    def get_torrents(self, params):
        instance = 'https://torrenther.com/'
        if 'instance' in params:
            instance = params['instance']
        torrents = self.get_torrenther(instance)
        return torrents 

    def get_items(self, params):
        return self.get_torrents(params)

